package com.jshoperxms.controller.mall.backstage.productsku;

import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.products.ProductSkuVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.ProductEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.ProductSkuT;
import com.jshoperxms.service.ProductSkuTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by sdywcd on 16/9/13.
 * Des:
 */
@Controller
@RequestMapping("/mall/productsku")
public class ProductskuTController extends BaseTController implements IBaseCtrl<ProductSkuT>{

    @Resource
    private ProductSkuTService productSkuTService;
    //数据形式
    private Map<String, Object> responsedata = new HashMap<>();


    /**
     *
     * @api {post} /mall/productsku/save 保存sku
     * @apiName 保存sku
     * @apiGroup  ProductService
     * @apiDescription 后台管理员添加sku
     * @apiVersion 0.0.1
     * @apiParam {String} isshare 是否共享sku 1共享 0不共享
     * @apiParam {String} name 名称
     * @apiParam {String} note 说明
     * @apiParam {String} skuval sku值
     * @apiParam {int} sort 排序
     * @apiParam {String} tag 标记
     * @apiParam {String} type 类型 1文字 2颜色
     * @apiParam {String} status 记录状态 启用或者禁用
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody ProductSkuT rq) {
        ProductSkuT bean=new ProductSkuT();
        bean.setId(this.serial.Serialid(SerialKeys.PRODUCTSKUT));
        bean.setCreatetime(DateTools.getSystemTimeBi());
        bean.setCreatorid(BaseTools.getAdminCreateId());
        bean.setIsshare(rq.getIsshare());
        bean.setName(rq.getName());
        bean.setNote(rq.getNote());
        bean.setSkuval(rq.getSkuval());
        bean.setSort(rq.getSort());
        bean.setStatus(rq.getStatus());
        bean.setStoreid(StaticKey.EMPTY);
        bean.setStorename(StaticKey.EMPTY);
        bean.setTag(rq.getTag());
        bean.setType(rq.getType());
        bean.setUpdatetime(DateTools.getSystemTimeBi());
        bean.setVersiont(1);
        this.productSkuTService.save(bean);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    /**
     *
     * @api {post} /mall/productsku/find 查询一条sku
     * @apiName 查询一条sku
     * @apiGroup  ProductService
     * @apiDescription 查询一条sku
     * @apiVersion 0.0.1
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     * @apiSuccess {ProductSkuT} bean 数据对象
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody ProductSkuT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            ProductSkuT bean=this.productSkuTService.findByPK(ProductSkuT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,TagWords.INVALIDDATA);
            }
        }
        return Response.success(responsedata);
    }

    /**
     *
     * @api {post} /mall/productsku/del 删除sku
     * @apiName 删除sku
     * @apiGroup  ProductService
     * @apiDescription 后台管理员删除sku
     * @apiVersion 0.0.1
     * @apiParam {String} id sku id
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody ProductSkuT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(),TagWords.SPLITDOT);
            for(String s:ids){
                ProductSkuT bean=this.productSkuTService.findByPK(ProductSkuT.class,s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.productSkuTService.update(bean);
                }
            }responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }


    /**
     *
     * @api {post} /mall/productsku/update 更新sku
     * @apiName 更新sku
     * @apiGroup  ProductService
     * @apiDescription 后台管理员更新sku
     * @apiVersion 0.0.1
     * @apiParam {String} isshare 是否共享sku 1共享 0不共享
     * @apiParam {String} name 名称
     * @apiParam {String} note 说明
     * @apiParam {String} skuval sku值
     * @apiParam {int} sort 排序
     * @apiParam {String} tag 标记
     * @apiParam {String} type 类型 1文字 2颜色
     * @apiParam {String} status 记录状态 启用或者禁用
     * @apiParam {String} id
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody ProductSkuT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            ProductSkuT bean=this.productSkuTService.findByPK(ProductSkuT.class,rq.getId());
            if(bean!=null){
                List<ProductSkuVo>productSkuVos=new ArrayList<>();
                List<ProductSkuVo>list= GsonJson.parseJsonToData(rq.getSkuval(),ProductSkuVo.class);
                for(ProductSkuVo ps:list){
                    ps.setSkuname(bean.getName());
                    productSkuVos.add(ps);
                }
                bean.setIsshare(rq.getIsshare());
                bean.setName(rq.getName());
                bean.setNote(rq.getNote());
                bean.setSkuval(GsonJson.parseDataToJson(productSkuVos));
                bean.setSort(rq.getSort());
                bean.setTag(rq.getTag());
                bean.setType(rq.getType());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.productSkuTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }
    /**
     *
     * @api {post} /mall/productsku/findAll 查询所有共享的sku
     * @apiName 查询所有共享的sku
     * @apiGroup  ProductService
     * @apiDescription 查询所有共享的sku
     * @apiVersion 0.0.1
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     * @apiSuccess {List} beanlist 数据集合
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/findAll",method= RequestMethod.POST)
    @Override
    public ResponseEntity findAll() {
        Criterion criterion = Restrictions.and(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("isshare", ProductEnums.ProductSkuIsShare.SHARE.getState()));
        List<ProductSkuT> beanlist = this.productSkuTService.findByCriteria(ProductSkuT.class, criterion, Order.desc(TagWords.UPDATETIME));
        List<ProductSkuVo> skubeanlist=new ArrayList<>();
        for(Iterator<ProductSkuT> it=beanlist.iterator();it.hasNext();) {
            ProductSkuT bean = it.next();
            List<ProductSkuVo> plist = GsonJson.parseJsonToData(bean.getSkuval(), ProductSkuVo.class);
            skubeanlist.addAll(plist);
        }
        responsedata.put(TagWords.BEANLIST, skubeanlist);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }


    /**
     *
     * @api {post} /mall/productsku/findByPage 查询sku列表
     * @apiName  查询sku列表
     * @apiGroup  ProductService
     * @apiDescription 后台管理员查询sku列表 1，区分是否有排序，是否有搜索，然后进行相应的业务方法调用
     * @apiVersion 0.0.1
     * @apiParam {SearchModel} searchModel 搜索模型对象
     * @apiParam {String} search 快捷搜索对象
     * @apiParam {String} ordervalue 排序对象
     * @apiParam {String} ordertype 排序方式
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     * @apiSuccess {map} data 搜索结果对象
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */
    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion;
            Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            Criterion criterion2=null;

            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion2=Restrictions.like("name",searchModel.getName(), MatchMode.ANYWHERE);
            }
            if(StringUtils.isNotBlank(search)){
                criterion2=Restrictions.like("name",search,MatchMode.ANYWHERE);
            }
            if(criterion2!=null){
                criterion=Restrictions.and(criterion1).add(criterion2);
                int records=this.productSkuTService.count(ProductSkuT.class,criterion).intValue();
                searchModel.setRecordsTotal(records);
                searchModel.setRecordsFiltered(records);
                responsedata.put(TagWords.RECORDSTOTAL,records);
                responsedata.put(TagWords.RECORDSFILTERED,records);
                List<ProductSkuT> list = this.productSkuTService.findByCriteriaByPage(
                        ProductSkuT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                        lineSize);
                this.processPageList(list);
            }
        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }

    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion;
        Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        Criterion criterion2=Restrictions.like("name",search,MatchMode.ANYWHERE);
        criterion=Restrictions.and(criterion1).add(criterion2);
        int records=this.productSkuTService.count(ProductSkuT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<ProductSkuT> list = this.productSkuTService.findByCriteriaByPage(
                ProductSkuT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.productSkuTService.count(ProductSkuT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("name",ordervalue,ordertype);
        List<ProductSkuT> list = this.productSkuTService.findByCriteriaByPage(
                ProductSkuT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<ProductSkuT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for(Iterator<ProductSkuT> it=list.iterator();it.hasNext();){
            ProductSkuT bean=it.next();
            List<ProductSkuVo>plist=GsonJson.parseJsonToData(bean.getSkuval(), ProductSkuVo.class);
            List<String>gst=new ArrayList<String>();
            for(ProductSkuVo g:plist){
                gst.add(g.getSkuval());
            }
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id",bean.getId());
            cellMap.put("name",bean.getName());
            cellMap.put("tag",bean.getTag());
            cellMap.put("isshare",ProductEnums.ProductSkuIsShare.getName(bean.getIsshare()));
            cellMap.put("type", ProductEnums.ProductSkuType.getName(bean.getType()));
            cellMap.put("skuval",StringUtils.join(gst.toArray(),TagWords.SPLITDOT));
            cellMap.put("note",bean.getNote());
            cellMap.put("sort",bean.getSort());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA,data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
